<?php

namespace app\common;


use app\model\Users;
use app\model\UsersAd;
use app\model\UsersChatgpt;
use app\tool\Http;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\facade\Log;

class GptService
{
    public static int $tokens=2048;

    /**
     * 提问
     * @param $msg
     * @return bool|string
     */
    static function ask($msg){

        return Http::post('http://chatgpt.weigangwan.hk/chatgpt/send',[
            'msg'=>$msg,
        ]);
    }
	
	/**
	 * GPT次数减少
	 * @param $uid
	 * @param $num
	 * @param $content
	 * @return void
	 * @throws DataNotFoundException
	 * @throws DbException
	 * @throws ModelNotFoundException
	 */
	static function decGptNum($uid,$num,$content){
		
		if ($num<=0){
			throw new Exception('gpt_num错误',0);
		}
		
		$users = Users::find($uid);
		if ($users->gpt_num<$num){
			throw new Exception('次数不足',1);
		}
		for($i=0;$i<$num;$i++){
			UsersChatgpt::create(['users_id'=>$uid,'content'=>$content]);
		}
		$users->gpt_num -= $num;
		$users->save();
	}
	
//	/**
//	 * 获取gpt剩余次数
//	 * @param $uid
//	 * @return int
//     * @throws DataNotFoundException
//	 * @throws DbException
//	 * @throws ModelNotFoundException
//	 */
//	static function gpt_num($uid)
//	{
//		//今天看广告次数
//		$ad = UsersAd::where(['users_id'=>$uid])->whereTime('createtime','today')->count(); //最多3次
//
//		//今天发送问题次数
//		$count = UsersChatgpt::where(['users_id'=>$uid])->whereTime('createtime','today')->count();
//
//		$users = Users::find($uid);
//		if ($users->vip_expire>=time()){
//			//会员
//			//今天剩余数量
//			$num = 50 + $ad - $count;
//		}else{
//			//非会员
//			$twodays_after = strtotime('+2 day',$users->getData('createtime'));
//			if ($twodays_after>=time()){
//				//新用户注册未超过两天
//				$num = 3 +$ad - $count;
//			}else{
//				//注册超过两天
//				$num= 0 + $ad - $count;
//			}
//		}
//		return $num;
//	}
}